Skip to content

fix(isCreditCard): fix regex anchoring in mastercard and unionpay patterns#2721

Open
xxiaoxiong wants to merge 1 commit into
validatorjs:masterfrom
xxiaoxiong:fix/mastercard-regex-anchoring-2717
Open

fix(isCreditCard): fix regex anchoring in mastercard and unionpay patterns#2721
xxiaoxiong wants to merge 1 commit into
validatorjs:masterfrom
xxiaoxiong:fix/mastercard-regex-anchoring-2717

Conversation

@xxiaoxiong
Copy link
Copy Markdown

Fixes #2717

Why
The Mastercard regex /^5[1-5][0-9]{2}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/ has an anchoring bug. Due to | having lower precedence than ^ and $, the regex engine parses it as two separate patterns:

  1. ^5[1-5][0-9]{2} — start-anchored only, matching any string beginning with 51XX-55XX (e.g. "5108" returns true)
  2. (222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$ — end-anchored only

The same issue affects the unionpay pattern where an extra ^ anchor appears inside a group.

Changes

  • mastercard: Wrapped the entire alternation in (?:...) so both ^ and $ anchor the full pattern: /^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/
  • unionpay: Removed the inner ^ anchor and wrapped in (?:...): /^(?:6[27][0-9]{14}|81[0-9]{14,17})$/

Updated component: src/lib/isCreditCard.js

Testing

  • isCreditCard("5108") now returns false (was true)
  • isCreditCard("5105105105105100") still returns true (valid Mastercard)
  • All provider-specific tests continue to work

Surface area

  • Validation / isCreditCard
  • Bug fix

@codecov
Copy link
Copy Markdown

codecov Bot commented May 26, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (7fdc788) to head (5d3548b).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #2721   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          114       114           
  Lines         2587      2587           
  Branches       656       656           
=========================================
  Hits          2587      2587           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

isCreditCard: Mastercard regex anchoring bug accepts 4-digit and partial strings

1 participant